package gui;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.border.BevelBorder;

public class ScreenCapture {
	private JMenuItem capture;
	private JPopupMenu SC;
	private Robot robot;
	private JFrame f;

	public ScreenCapture(JFrame f) {
		try {
			robot = new Robot();
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.f = f;
	}

	private JMenuItem getAddRoom() {
		if (capture == null) {
			capture = new JMenuItem();
			capture.setText("Save graph");
			capture.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					final JFileChooser fc = new JFileChooser();
					int returnVal = fc.showSaveDialog(f);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						Thread t = new Thread(new Runnable() {
							@Override
							public void run() {
								try {
									Thread.sleep(350);
									File file = fc.getSelectedFile();
									Point p = f.getLocation();
									int w, h;
									p.x += 6;
									p.y += 28;
									w = f.getWidth() - 12;
									h = f.getHeight() - 34;
									Rectangle rr = new Rectangle(p.x, p.y, w, h);
									BufferedImage sc = robot
											.createScreenCapture(rr);
									try {
										ImageIO.write(sc, "png", file);
									} catch (IOException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}
								} catch (Exception e) {
									// TODO: handle exception
								}

							}
						});
						t.start();
					}

				}
			});
		}
		return capture;
	}

	public JPopupMenu getRoomPopup() {
		if (SC == null) {
			SC = new JPopupMenu();
			SC.setSize(new Dimension(80, 120));
			SC.add(getAddRoom());
			SC.setBorder(new BevelBorder(BevelBorder.RAISED));

		}
		return SC;
	}

}
